from rest_framework import serializers
from rest_framework.exceptions import APIException
from libs.lqz_jwt import TokenManager
from .models import UserInfo
from permission.serializer import RolesSerializer

class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def _get_user(self, attrs):
        import re
        username = attrs.get('username')
        if re.match(r'^1[3-9][0-9]{9}$', username):
            user = UserInfo.objects.filter(phone=username).first()
        else:
            user = UserInfo.objects.filter(username=username).first()
        if not user:
            raise APIException(detail='用户名错误')
        password = attrs.get('password')
        if not user.check_password(password):
            raise APIException(detail='密码错误')
        if not user.is_active:
            raise APIException(detail='您已被锁定，不能登录')
        return user

    def _get_token(self, user):
        token = TokenManager.get_token(user)
        return token

    def validate(self, attrs):
        user = self._get_user(attrs)
        # user签发token
        token = self._get_token(user)
        self.context['token'] = token
        self.context['username'] = user.username
        self.context['avatar'] = str(user.avatar)
        return attrs




class UserSerializer(serializers.ModelSerializer):
    role_list=RolesSerializer(source='roles',many=True)
    class Meta:
        model = UserInfo
        fields = ['id','username','is_active','email','create_time',
                  'nick_name','gender','phone','avatar','enabled','is_login',
                  'dept','job','roles','role_list']


class UserCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = ['id','username','is_active','email','nick_name','gender','phone','enabled',
                  'dept','job','roles']